package com.example.handler;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class Handler_Thread extends AppCompatActivity {
    EditText handler_Thread_EditText;


    static final String UPPER_NUM = "upper";
    CalThread calThread;

    // 定义一个线程类
    class CalThread extends Thread//计算质数
    {
        public Handler mHandler;

        public void run() {
            Looper.prepare();// Looper.prepare()来给线程创建消息循环

            mHandler = new Handler() {
                int i=0;
                // 定义处理消息的方法
                @Override
                public void handleMessage(Message msg) {

                    if (msg.what == 0x123) {
                        int upper = msg.getData().getInt("1");
                            handler_Thread_EditText.setText( i+ "   " + upper);
                            i++;
                    }
                }
            };
            Looper.loop();//Looper.loop()来使消息循环起作用。
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_thread);
        handler_Thread_EditText = (EditText) findViewById(R.id.handler_Thread_EditText);
        Button handler_Thread_Button = (Button) findViewById(R.id.handler_Thread_Button);
        calThread = new CalThread();
        // 启动新线程
        calThread.start();

        Message msg = new Message();
        msg.what = 0x123;
        Bundle bundle = new Bundle();
        bundle.putInt("1", 100);
        msg.setData(bundle);
        handler_Thread_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                calThread.mHandler.sendMessage(msg);
                calThread. mHandler.sendEmptyMessage(0x123);

            }
        });
    }

}